package com.blog.admin.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.blog.admin.pojo.auth.Role;
import com.blog.admin.service.RoleService;
import com.blog.admin.utils.ResultVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;

import cn.hutool.core.util.StrUtil;

@Controller
@RequestMapping(value = "/admin/role")
public class RoleController {

	@Autowired
	private RoleService roleService;

	@ModelAttribute
	public Role getRole(String id, Model mode) {
		Role role = new Role();
		if (StrUtil.isNotBlank(id)) {
			role = roleService.getRoleById(Integer.valueOf(id));
		}
		mode.addAttribute("role", role);
		return role;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@RequiresPermissions("role:list")
	@ResponseBody
	public PageInfo<Role> submitLogin(@RequestParam("page") String pageNum, @RequestParam("limit") String pageSize) {

		Page<Role> roles = roleService.getRoleList(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
		PageInfo<Role> pageInfo = new PageInfo<>(roles);
		return pageInfo;
	}

	@RequestMapping(value = "/addRolePage", method = RequestMethod.GET)
	public String addRolePage(String id, Model model) {
		model.addAttribute("id", id);
		return "pages/sysManager/addrolePage";
	}

	@RequestMapping(value = "/getMenuTree", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> getMenuTree(String id) {
		return roleService.getMenuTree(id);
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@RequiresPermissions("role:delete")
	@ResponseBody
	public boolean deleteRole(String id) {
		return roleService.deleteRole(id);
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@RequiresPermissions("role:save")
	@ResponseBody
	public JSONObject save(String treeids, @Valid Role role, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			for (ObjectError error : bindingResult.getAllErrors()) {
				return ResultVo.fail(error.getDefaultMessage());
			}
		}
		if (role.getId() != null) { // 更新操作
			roleService.update(role, treeids);
		} else {
			roleService.insert(role, treeids);
		}
		return ResultVo.success("保存成功");
	}
}
